package cn.turboinfo.fuyang.api.gateway.share.framework.http.interceptor;

import cn.turboinfo.fuyang.api.domain.share.usecase.authorize.ShareAuthorizeVerificationUseCase;
import cn.turboinfo.fuyang.api.entity.common.exception.common.DataNotExistException;
import cn.turboinfo.fuyang.api.gateway.share.constant.ShareRestConstants;
import cn.turboinfo.fuyang.api.gateway.share.framework.http.ShareResponseBodyWrapperException;
import cn.turboinfo.fuyang.api.gateway.share.framework.http.context.ShareRequestContextHolder;
import cn.turboinfo.fuyang.api.gateway.web.framework.http.interceptor.BaseHandlerInterceptorAdapter;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class ShareAccountAuthInterceptor extends BaseHandlerInterceptorAdapter {

    private final ShareAuthorizeVerificationUseCase shareAuthorizeVerificationUseCase;

    public ShareAccountAuthInterceptor(ShareAuthorizeVerificationUseCase shareAuthorizeVerificationUseCase) {
        this.shareAuthorizeVerificationUseCase = shareAuthorizeVerificationUseCase;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String appId = request.getParameter("appId");
        String appSecret = request.getParameter("appSecret");
        String uscc = request.getParameter("uscc");

        if (handler instanceof HandlerMethod) {
            try {
                ShareAuthorizeVerificationUseCase.OutputData outputData = shareAuthorizeVerificationUseCase
                        .execute(ShareAuthorizeVerificationUseCase
                                .InputData
                                .builder()
                                .appId(appId)
                                .appSecret(appSecret)
                                .uscc(uscc)
                                .build());

                if (outputData.isPass()) {
                    val requestContext = ShareRequestContextHolder.current();
                    requestContext.setCompanyId(outputData.getCompany().getId());
                    requestContext.setUscc(uscc);
                    return true;
                } else {
                    throw new ShareResponseBodyWrapperException(ShareRestConstants.RC_ERROR_UNAUTHENTICATED, "认证信息不匹配");
                }

            } catch (DataNotExistException e) {
                throw new ShareResponseBodyWrapperException(ShareRestConstants.RC_ERROR_UNAUTHENTICATED, "未包含认证信息");
            }
        }
        return true;

    }
}
